<template>
  <div class="common-page">
    <div class="common-page-content">
      <el-card class="common-card">
        <!-- 搜索条件区域 -->
        <div class="search-section">
          <ul class="search-form">
            <li class="form_item">
              <label class="label">部门</label>
              <div class="input_box">
                <div class="input_box">
                  <el-select v-model="form.did" filterable class="input" @change="changeDepart">
                    <el-option v-for="item in depart_option" :key="item.id" :label="item.dpname" :value="item.id">
                      <span v-html="item.html" style="letter-spacing:6px"></span>
                      {{ item.dpname }}
                    </el-option>
                  </el-select>
                </div>
                <el-select v-model="form.eid" filterable class="input">
                  <el-option label="全部" value=" "></el-option>
                  <el-option v-for="item in user_option" :key="item.id" :label="item.realname"
                    :value="item.id"></el-option>
                </el-select>
              </div>
            </li>
            <li class="form_item">
              <label class="label">星期</label>
              <div class="input_box">
                <el-select v-model="form.w" clearable class="input">
                  <el-option label="全部" value=" "></el-option>
                  <el-option v-for="(item, index) in w" :key="index" :label="item" :value="index"></el-option>
                </el-select>
              </div>
            </li>
            <li class="form_item">
              <label class="label">IP</label>
              <div class="input_box">
                <el-input class="input" v-model.trim="form.ip"></el-input>
              </div>
            </li>
            <li class="form_item">
              <label class="label">时间</label>
              <div class="input_box">
                <el-date-picker v-model="times" type="daterange" align="right" unlink-panels range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                  :shortcuts="shortcuts"></el-date-picker>
              </div>
            </li>
            <li class="form_item">
              <div class="input_box">
                <el-button type="primary" @click="handleSearch" class="search-btn">
                  搜索
                </el-button>
              </div>
            </li>
          </ul>
        </div>

        <!-- 表格区域 -->
        <div class="common-table-container" >
          <table class="common-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>用户姓名</th>
                <th>登录IP</th>
                <th>星期（一~日）</th>
                <th>登录时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in tableData" :key="index">
                <td>{{ item.id }}</td>
                <td>{{ item.realname }}</td>
                <td>{{ item.ip }}</td>
                <td>{{ w[item.w] }}</td>
                <td>{{ item.addtime }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页区域 -->
        <div class="common-pagination-section">
          <el-pagination :current-page="pagination.currentPage" :page-size="pagination.pageSize" :small="true"
            :background="true" layout="total, prev, pager, next, jumper" :total="pagination.total" pager-count="5"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" class="common-pagination" />
            <button class="tg_btm" @size-change="handleSizeChange">跳转</button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { logsApi } from '@/api/logs'
import { useUserStore } from '@/stores/user'
import TOOLS from '@/utils/tools'
// 获取部门选项
const init_option = useUserStore().init_option?.common_option
const depart_option = TOOLS.Flaten(init_option?.depart_option || [])

// 星期数组
const w = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]

// 响应式数据
const form = reactive({
  did: '',
  eid: ' ',
  w: ' ',
  ip: '',
  stime: '',
  etime: ''
})

// 时间选择器
const times = ref([])

// 使用通用的日期选择器快捷选项
const shortcuts = TOOLS.DatePickerShortcuts
// 用户选项
const user_option = ref([])

// 表格数据
const tableData = ref([])

// 表格加载状态
const tableLoading = ref(false)

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 30,
  total: 0
})

// 初始化
onMounted(() => {
  loadLoginLogList()
  if (depart_option.length > 0) {
    form.did = depart_option[0].id;
    get_sub_department_employee(form.did)
  }
})

// ==================== 数据加载方法 ====================

/**
 * 加载登录日志列表
 */
const loadLoginLogList = async () => {
  try {
    tableLoading.value = true

    // 构建搜索条件
    const searchData = {
      did: form.did,
      eid: form.eid,
      w: form.w,
      ip: form.ip,
      stime: form.stime,
      etime: form.etime
    }

    // 获取当前分页参数
    const page = pagination.currentPage

    // 调用API获取登录日志列表数据
    const response = await logsApi.getLoginLogList(searchData, page)

    // 检查API响应状态并更新数据
    if (response.status) {
      tableData.value = response.data.list || []
      pagination.total = Number(response.data.count) || 0
    } else {
      tableData.value = []
      pagination.total = 0
      ElMessage.error(response.msg || '获取登录日志列表失败')
    }
  } catch (error) {
    console.error('加载登录日志列表失败:', error)
    ElMessage.error('加载登录日志列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    tableLoading.value = false
  }
}

// 部门用户数据缓存
const departmentUsersCache = new Map()

/**
 * 获取指定部门下的员工列表（带缓存）
 */
const get_sub_department_employee = async (did) => {
  if (!did) {
    user_option.value = []
    return
  }

  // 检查缓存
  if (departmentUsersCache.has(did)) {
    user_option.value = departmentUsersCache.get(did)
    return
  }

  try {
    const response = await logsApi.get_sub_department_employee(did)
    const users = response.data || []
    // 缓存结果
    departmentUsersCache.set(did, users)
    user_option.value = users
  } catch (error) {
    console.error('获取部门员工失败:', error)
    user_option.value = []
  }
}

// ==================== 事件处理方法 ====================

/**
 * 处理部门变化
 */
const changeDepart = (did) => {
  form.eid = '' // 清空员工选择
  if (did) {
    get_sub_department_employee(did)
  } else {
    user_option.value = []
  }
}

// 创建分页处理器
const paginationHandlers = TOOLS.createPaginationHandlers(
  pagination,
  null, // 这个页面没有 form.page_size
  () => loadLoginLogList(),
  { scrollToTopOnPageChange: true }
)

// 使用公共分页处理方法
const { handleSizeChange, handleCurrentChange } = paginationHandlers

/**
 * 处理搜索
 */
const handleSearch = async () => {
  // 处理时间范围
  if (times.value && times.value.length === 2) {
    form.stime = times.value[0]
    form.etime = times.value[1]
  } else {
    form.stime = ''
    form.etime = ''
  }

  // 重置到第一页
  pagination.currentPage = 1
  await loadLoginLogList()
  TOOLS.scrollToTop()
}
</script>
